package com.wss.lsl.lucene.demo;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.QueryParser.Operator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

// IK中文分词器支持 lucene 3.4
public class IKAnalyzerDemo {
	
	public static void main(String[] args) {

		String fieldName = "text";
		String text = "IK Analyzer是一个结合词典分词和文法分词的中文分词开源工具包。它使用了全新的正向迭代最细粒度切分算法。";
		
		Analyzer analyzer = new IKAnalyzer();
		Directory directory = null;
		IndexWriter writer = null;
		IndexReader reader = null;
		IndexSearcher searcher = null;
		
		try {
			directory = new RAMDirectory();
			writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_34, analyzer));
			Document document = new Document();
			document.add(new Field(fieldName, text, Field.Store.YES, Field.Index.ANALYZED));
			document.add(new Field("ID", "100000", Field.Store.YES, Field.Index.NOT_ANALYZED));
			writer.addDocument(document);
			writer.close();
			
			String keyword = "中文分词工具包";
			reader = IndexReader.open(directory);
			searcher = new IndexSearcher(reader);
			QueryParser parser = new QueryParser(Version.LUCENE_34, fieldName, analyzer);
			parser.setDefaultOperator(Operator.AND);
			Query query = parser.parse(keyword);
			TopDocs topDocs = searcher.search(query, 5);
			int count = topDocs.totalHits;
			System.out.println("Found " + count + " hits.");
			for(ScoreDoc hit : topDocs.scoreDocs){
				Document doc = searcher.doc(hit.doc);
				System.out.println("text: "+ doc.get(fieldName) + "\t" + doc.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(directory != null){
				try {
					directory.close();
				} catch (IOException e) {
					e.printStackTrace();
				};
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
	}
}
